package com.camel.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.camel.base.model.TbApi;
import com.camel.base.model.TbDatasource;
import com.camel.base.service.TbApiService;
import com.camel.base.service.TbDatasourceService;
import com.camel.core.controller.BaseCommonController;
import com.camel.core.exceptions.CustomException;
import com.camel.core.service.BaseCommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;

/**
 * @author camel
 */
@RestController
@RequestMapping("tbApi")
public class TbApiController extends BaseCommonController<TbApi> {

    @Autowired
    private TbApiService<TbApi> service;

    @Autowired
    private TbDatasourceService<TbDatasource> datasourceService;


    @Override
    public boolean exist(TbApi entity) {
        if(ObjectUtils.isEmpty(entity.getSourceId())) {
            throw new CustomException("无效的数据源");
        }
        TbDatasource datasource = datasourceService.getById(entity.getSourceId());
        if(ObjectUtils.isEmpty(datasource)) {
            throw new CustomException("无效的数据源");
        }
        return service.count(new QueryWrapper<TbApi>()
                .eq("request_url", entity.getRequestUrl())
        ) > 0;
    }

    @Override
    public boolean deleteAble(Serializable id) {
        TbApi byId = service.getById(id);
        if (ObjectUtils.isEmpty(byId)) {
            throw new CustomException("删除失败: " + getMouduleName() + "不存在");
        }
        return true;
    }

    @Override
    public BaseCommonService<TbApi> getiService() {
        return service;
    }

    @Override
    public String getMouduleName() {
        return "接口";
    }
}
